package com.yang.studentsapp.ui.campus;


import android.content.Context;
import android.os.Bundle;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;


import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.yang.studentsapp.Banner;
import com.yang.studentsapp.BannerImageViewUtils;
import com.yang.studentsapp.CycleViewPager;
import com.yang.studentsapp.DisplayUtils;
import com.yang.studentsapp.Grid;
import com.yang.studentsapp.Home;
import com.yang.studentsapp.ImageCycleViewListener;
import com.yang.studentsapp.PresenterCampus;
import com.yang.studentsapp.R;
import com.yang.studentsapp.presenter.IView;
import com.yang.studentsapp.presenter.IViewSuccess;
import com.yang.studentsapp.ui.adapter.BaseViewHolder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ${Ян-Вэнь-Чао} on 2016/10/10.
 * 学校
 */
public class SchoolFragment extends Fragment implements IView {
    private RecyclerView recyclerView;
    private RecyclerView recycgrid;
    List<Home> list = new ArrayList<Home>();
    MyAdapter adapter;

    List<Grid> listgrid = new ArrayList<>();

    private CycleViewPager mCycleViewPager;
    ArrayList<Banner> banners;

    PresenterCampus presenterCampus;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_school, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.school_recy_view);
        recycgrid = (RecyclerView) view.findViewById(R.id.school_recy_gridview);
        initView();
        banners = new ArrayList<>();
        mCycleViewPager = (CycleViewPager) getActivity().getFragmentManager().findFragmentById(R.id.life_fragment_banner);
        getDataFromServer();
        gridView();

        return view;
    }

//R.color.cornflowerblue R.color.red R.color.lawngreen R.color.goldenrod  R.color.mediumslateblue
    private void initView() {
//        recyclerView.addItemDecoration(new RecycleViewDivider(getContext(),
//                LinearLayoutManager.VERTICAL,0,getResources().getColor(R.color.bai)));
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
//        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        Home home = new Home("院校概况",getResources().getColor(R.color.cornflowerblue) , R.drawable.home_colleges);
        Home home1 = new Home("就业创业",getResources().getColor(R.color.red), R.drawable.home_job);
        Home home2 = new Home("院系专业",getResources().getColor(R.color.lawngreen),R.drawable.home_department);
        Home home3 = new Home("校园新闻",getResources().getColor(R.color.goldenrod),R.drawable.home_news);
        Home home4 = new Home("通知公告",getResources().getColor(R.color.mediumslateblue),R.drawable.home_notice);
        list.add(home);
        list.add(home1);
        list.add(home2);
        list.add(home3);
        list.add(home4);
        if (list != null) {
            Log.v("tag", "list天价数据成功");
        }
        adapter = new MyAdapter(getContext(), list, R.layout.recycler_item);
        if (adapter != null) {
        Log.v("tag", "数据加载！！！！");
        }
        if (recyclerView != null) {
            recyclerView.setAdapter(adapter);
            Log.i("tag", "recyclerView加载成功");
        } else {
            Log.e("tag", "recyclerView加载失败");
        }


    }


    private void gridView() {
        presenterCampus = new PresenterCampus(this);
        final com.yang.studentsapp.ui.adapter.BaseAdapter adapter =
                new com.yang.studentsapp.ui.adapter.BaseAdapter<Grid>(getContext(),
                        listgrid, R.layout.recycler_grid_item) {

                    @Override
                    protected void convert(Context mContext, BaseViewHolder holder, Grid grid) {
                        int windowwidth = DisplayUtils.getWidthPx();
//                        View view = holder.getView(R.layout.recycler_grid_item);
//                        int ViewWidth = (windowwidth - DisplayUtils.dip2px((float) 30)) / 3;
//                        RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) view.getLayoutParams();
//                        params.width = ViewWidth;
//                        recycgrid.setLayoutParams(params);
                        Glide.with(getContext()).load(grid.getUrl())
                                .placeholder(R.mipmap.ic_launcher)
                                .into((ImageView) holder.getView(R.id.recycler_grid_item_image));
                        holder.setText(R.id.recycler_grid_item_text,
                                grid.getTitle());
                    }
                };
        if (recycgrid != null) {
        recycgrid.setAdapter(adapter);
            Log.v("tag", "recycgrid加载成功");
        }
//recyclerView.getChildType
        presenterCampus.getSchoolNews(new IViewSuccess<List<Grid>>() {
            @Override
            public void onSuccess(List<Grid> data) {
                Toast.makeText(getContext(), "success!!!" + data.size(), Toast.LENGTH_SHORT).show();
                adapter.updateData(data);

            }
        });
        GridLayoutManager manager = new GridLayoutManager(getContext(), 3);
        recycgrid.setLayoutManager(manager);

    }
    private void getDataFromServer() {
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        JsonObjectRequest request =
                new JsonObjectRequest(Request.Method.GET,
                        "https://studentapp-kblog.rhcloud.com/api/school/slider?signature=ad569e516e5d6d1b10e607956fd7059f",
                        null,
                        new Response.Listener<JSONObject>(){
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    JSONArray ja = jsonObject.getJSONArray("data");
                                    System.out.println("--->"+ja.toString());
                                    Banner banner ;
                                    for (int i = 0; i < ja.length(); i++) {
                                        JSONObject jo1 = ja.getJSONObject(i);
                                        banner = new Banner(
                                                jo1.getString("school_slider_url_ab")
                                        );
                                        banners.add(banner);
                                    }
                                    setBanner(banners);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        }, new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                });

        requestQueue.add(request);
        requestQueue.start();
    }
    private void setBanner(List<Banner> banners) {
        for (Banner banner : banners) {
            bannerImageView = BannerImageViewUtils.getImageView(getContext());

//            Picasso.with(MainActivity.this)
//                    .load(banner.getImageUrl())
//                    .placeholder(R.drawable.life_banner)
//                    .error(R.drawable.life_banner)
//                    .into(bannerImageView);

            Glide.with(getContext()).load(banner.getImageUrl()).centerCrop()
                    .placeholder(R.drawable.life_banner)
                    .crossFade().into(bannerImageView);

            mImageViews.add(bannerImageView);
        }

        //重新添加第一个view
        bannerImageView = BannerImageViewUtils.getImageView(getContext());
        Glide.with(getContext()).load(banners.get(banners.size() - 1).getImageUrl()).centerCrop()
                .placeholder(R.drawable.life_banner)
                .crossFade().into(bannerImageView);
        mImageViews.add(0, bannerImageView);
        //重新添加最后一个view
        bannerImageView = BannerImageViewUtils.getImageView(getContext());
        Glide.with(getContext()).load(banners.get(0).getImageUrl()).centerCrop()
                .placeholder(R.drawable.life_banner)
                .crossFade().into(bannerImageView);
        mImageViews.add(bannerImageView);

        // 设置循环，在调用setData方法前调用
        mCycleViewPager.setCycle(true);
        // 在加载数据前设置是否循环
        mCycleViewPager.setData(mImageViews, banners, new ImageCycleViewListener() {
            @Override
            public void onImageClick(Object info, int position, View imageView) {

            }
        });
        //设置轮播
        mCycleViewPager.setWheel(true);
        // 设置轮播时间，默认5000ms
        mCycleViewPager.setTime(3000);
        //设置圆点指示图标组居中显示，默认靠右
        mCycleViewPager.setIndicatorCenter();
        mImageViews.clear();
    }
    private ImageView bannerImageView;
    private List<ImageView> mImageViews = new ArrayList<>();

    @Override
    public void onFail(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStart(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(String msg) {
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }

    class MyAdapter extends com.yang.studentsapp.ui.adapter.BaseAdapter<Home> {

        public MyAdapter(Context mContext, List<Home> mDatas, int mLayoutId) {
            super(mContext, mDatas, mLayoutId);
        }

        @Override
        protected void convert(Context mContext, BaseViewHolder holder, Home home) {
            holder.setText(R.id.recycler_item_text, home.getName())
                    .setBackgroundColor(R.id.recycler_item, home.getBannground())
                    .setImageResource(R.id.recycler_item_image, home.getIcon());
        }
    }
}
